const Koa=require('koa');
const session = require('koa-session');
const fs= require('fs');
const path = require('path');   //解析请求的地址    


let server = new Koa();
server.listen(8080);

function readFilePromise(path){
    return new Promise((resolve,reject)=>{
        fs.readFile(path,(err,data)=>{
            if(err){
                reject(err);
            }else{
                resolve(data.toString());
            }
        })
    })
}


server.use(async ctx=>{
    switch (ctx.request.host) {
        case 'ahth.aaa.com:8080':
            ctx.res.setHeader('Access-Control-Allow-Origin','*');
            //  用户数据
            let users={
                'blue':{pass:'123456',token:'b38721b1-8921-4aab-ac4c-64654eb4b8f3',age:18},
                'zhangsan':{pass:'987654',token:'1df0c506-3d0b-4c3a-a176-ad87b66df66d',age:19},
            }
            // 写接口
            switch (ctx.request.path) {
                //登陆/login?user:xxxx&pass=XXXX
                // =>{err:0,token:'b38721b1-8921-4aab-ac4c-64654eb4b8f3'}
                case '/login':
                    /* let {user,pass}=res.request.query;
                    if(!users[user]){
                        ctx.response.body={err:1,msg:'用户不存在'};
                    }else if(users[user].pass!=pass){
                        ctx.response.body={err:1,msg:'用户密码不正确'};
                    }else{
                        ctx.response.body={err:0,msg:'登录成功',token:users[user].token};
                    } */
                    let {user,pass}=res.request.query;
                    if(!users[user]){
                        ctx.response.body='用户不存在';
                    }else if(users[user].pass!=pass){
                        ctx.response.body='用户密码不正确';
                    }else{
                        ctx.redirect(`${ctx.request.query['src']}?token=${users[user].token}`);
                    } 
                    break;
                // 获取：/get_age?token=XXXXX
                // =>{err:0,age:xxx}
                case '/get_age':
                    let {token}=ctx.request.query;
                    let found=false;
                    let age=0;
                    for(let name in users){
                        if(users[name].token==token){
                            age=users[name].age;
                            found=true;
                        }
                    }
                    if(found){
                        ctx.response.body={err:0,age}
                    }else{
                        ctx.response.body={err:1,msg:'此token不存在'};
                    }
                    break;
            }


            break;
        case 'www.bbb.com:8080':
            ctx.response.body=await readFilePromise(`www_bbb${ctx.request.path}`);
            break;
        case 'www.ccc.com:8080':
            ctx.response.body=await readFilePromise(`www_bbb${ctx.request.path}`);
            break;
    }
})